package com.hang.ad.service.impl;

import com.hang.ad.constant.Constants;
import com.hang.ad.dao.AdUserDao;
import com.hang.ad.entity.AdUser;
import com.hang.ad.exceptions.AdException;
import com.hang.ad.service.IUserService;
import com.hang.ad.utils.CommonUtils;
import com.hang.ad.vo.CreateUserRequest;
import com.hang.ad.vo.CreateUserResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {
    @Autowired
    AdUserDao adUserDao;
    @Override
    @Transactional
    public CreateUserResponse createUser(CreateUserRequest request) throws AdException {
        //验证参数是否为空
        if (!request.validate()){
            throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        }
        //验证是否用户名重复
        AdUser oldUser = adUserDao.findByUsername(request.getUsername());
        if (oldUser != null){
            throw new AdException(Constants.ErrorMsg.SAME_NAME_ERROR);
        }
        //保存用户并返回response
        AdUser newUser = adUserDao.save(new AdUser(request.getUsername(), CommonUtils.md5(request.getUsername())));
        return new CreateUserResponse(newUser.getId(),newUser.getUsername(),newUser.getToken(),
                newUser.getCreateTime(),newUser.getUpdateTime());
    }
}
